package cn.dnf.exception;

import cn.dnf.enums.GlobalEnumCode;
import cn.dnf.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Component
@Slf4j
public class GlobalException {
    //标识所要捕获的异常类型
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.info("发生了exception异常:"+e.getMessage());
       return JsonResult.error(GlobalEnumCode.ERROR);

    }

    //捕捉我们的自定义异常
    @ExceptionHandler(GlobalCustomException.class)
    public JsonResult globalCustomException(GlobalCustomException e){
        e.printStackTrace();
        log.info("捕捉了exception异常:"+e.getErrorMessage()+"错误代码为："+e.getErrorCode());
        return JsonResult.error(e);

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sbr = new StringBuilder();

        e.getBindingResult().getAllErrors().forEach(item->{
            sbr.append(item.getDefaultMessage()).append(" ");
        });
        log.info("发生了exception异常:"+sbr.toString());
        return JsonResult.error(sbr.toString(),"10000");

    }
}
